package org.jeecg.modules.demo.crm.service.impl;

import com.alibaba.fastjson.JSONObject;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.Md5Util;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.demo.crm.entity.*;
import org.jeecg.modules.demo.crm.mapper.*;
import org.jeecg.modules.demo.crm.service.ICAdditionalRequestService;
import org.jeecg.modules.demo.crm.service.ICEmailService;
import org.jeecg.modules.demo.crm.service.ICNoticeService;
import org.jeecg.modules.demo.crm.service.ICProjectQuoteService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.List;

import static org.jeecg.modules.demo.crm.util.CommonConst.*;

/**
 * @Description: 通知
 * @Author: jeecg-boot
 * @Date:   2025-07-27
 * @Version: V1.0
 */
@Service
public class CNoticeServiceImpl extends ServiceImpl<CNoticeMapper, CNotice> implements ICNoticeService {

    @Autowired
    private CAdditionalRequestMapper cAdditionalRequestMapper;

    @Autowired
    private CNoticeMapper cNoticeMapper;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    private CWeixinMapper cWeixinMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private CProjectQuoteMapper cProjectQuoteMapper;

    @Autowired
    private CSubProjectMapper cSubProjectMapper;

    @Autowired
    private CTaskMapper cTaskMapper;

    @Autowired
    ICEmailService emailService;

    @Autowired
    CWxMsgMapper cWxMsgMapper;

    @Override
    public void gather() {
        //需求新增提醒
        additionalAdd();
        //需求审核结果--通过
        additionalAudit();
        //需求审核结果--驳回
        additionalReject();
        //需求----报价中
        additionalQuote();
        //需求--提交报价--提醒
        additionalQuoteCrate();
        //需求--报价审核--同意or驳回
        additionalQuoteAudit();
        //--------------------------------
        //子项目---项目指派成功
        subProjectCrate();
        //子项目--提交报价--审核提醒
        subProjectQuoting();
        //-----------------------------
        //计划任务--待处理--驳回
        taskPending();
        //计划任务--已处理
        taskProcessed();


    }

    /**
     * 发送邮件
     */
    @Override
    public void sendEmail() {
        List<CNotice> cNotices = cNoticeMapper.sendEmail();
        for (CNotice cNotice : cNotices) {
            try {
                if(StringUtils.isNotEmpty(cNotice.getMailNo())){
                    StringBuilder content = new StringBuilder();
                    content.append("<p><h1>" + cNotice.getTitle() + "--" +cNotice.getStatus() +"</h1></p>");
                    content.append("<p>处理人：" + cNotice.getHandler()+ "</p>");
                    content.append("<p>结果：" + cNotice.getResults() + "</p>");
                    if(StringUtils.isNotEmpty(cNotice.getUrl())){
                        content.append("<p><a href=\""+cNotice.getUrl()+" \" >点击查看</a></p>");
                    }
                    content.append("<hr>");
                    content.append("<br/>");
                    String taskId = emailService.addTaskEmail(cNotice.getUserId(), cNotice.getBusiness(), content.toString(), null);
                    cNotice.setMailStatus("已发送");
                    cNotice.setMailMsg("发送成功");
                    cNotice.setMailId(taskId);
                }else {
                    cNotice.setMailStatus("发送失败");
                    cNotice.setMailMsg("发送失败，邮箱号为空");
                }
                cNoticeMapper.updateById(cNotice);
            }catch (Exception e){
                cNotice.setMailStatus("发送失败");
                cNotice.setMailMsg(e.getMessage());
                cNoticeMapper.updateById(cNotice);
            }

        }


    }

    @Value("${wx.templateId}")
    private String templateId;


    @Override
    public void sendWx() {
        List<CNotice> cNotices = cNoticeMapper.sendWx();
        for (CNotice cNotice : cNotices) {
            if(StringUtils.isNotEmpty(cNotice.getWxOpenId())){
                try {
                    CWxMsg cwxMsg = new CWxMsg();
                    cwxMsg.setStatus("待发送");
                    cwxMsg.setUserId(cNotice.getId());
                    cwxMsg.setOpenId(cNotice.getWxOpenId());
                    cwxMsg.setTemplateId(templateId);
                    cwxMsg.setUrl(cNotice.getWxUrl());
                    cwxMsg.setBusiness(cNotice.getBusiness());

                    String thing41 = cNotice.getBusiness();
                    if (thing41 != null && thing41.length() > 17) {
                        thing41 = thing41.substring(0, 17) + "...";
                    }

                    String thing44 = cNotice.getTitle();
                    if (thing44 != null && thing44.length() > 17) {
                        thing44 = thing44.substring(0, 17) + "...";
                    }
                    String thing53 = cNotice.getHandler();
                    if (thing53 != null && thing53.length() > 17) {
                        thing53 = thing53.substring(0, 17) + "...";
                    }

                    String short_thing5 = cNotice.getStatus();
                    if (short_thing5 != null && short_thing5.length() > 17) {
                        short_thing5 = short_thing5.substring(0, 17) + "...";
                    }

                    String thing35 = cNotice.getResults();
                    if (thing35 != null && thing35.length() > 29) {
                        thing35 = thing35.substring(0, 29) + "...";
                    }

                    JSONObject body = new JSONObject();
                    body.put("thing41",thing41);//流程名称 20
                    body.put("thing44",thing44);//工单名称
                    body.put("thing53",thing53);//执行人
                    body.put("short_thing5",short_thing5);//工单状态
                    body.put("thing35",thing35);//处理结果 20
                    cwxMsg.setData(JSONObject.toJSONString(body));
                    cWxMsgMapper.insert(cwxMsg);
                    cNotice.setWxStatus("已发送");
                    cNotice.setWxMsg("已发送");
                    cNotice.setWxMsgId(cwxMsg.getId());

                } catch (Exception e) {
                    cNotice.setWxStatus("发送失败");
                    cNotice.setWxMsg(e.getMessage());
                }
            }else {
                cNotice.setWxStatus("发送失败");
                cNotice.setWxMsg("openId为空");
                cNotice.setWxMsgId("");
            }
            cNoticeMapper.updateById(cNotice);

        }

    }

    /**
     * 计划任务--已处理
     */
    private void taskProcessed() {
        List<CTask> cTasks = cTaskMapper.taskProcessed();
        for (CTask vo : cTasks) {
            //提醒项目负责人
            List<SysUser> userList = getRoleUser(ROLE_PROJECT_LEADER);
            for (SysUser sysUser : userList) {
                //提醒分配的负责人
                msgFactory(sysUser.getId(),
                        TASK_PROCESSED,
                        vo.getName(),
                        vo.getUpdateBy(),
                        vo.getProcessingStatus(),
                        "计划任务-已处理-待审核",
                        WX_TASK_DETAIL.replace("{id}",vo.getId()),
                        TASK_DETAIL
                );
            }


        }
    }

    /**
     * 计划任务--待处理--驳回
     */
    private void taskPending() {
        List<CTask> cTasks = cTaskMapper.taskPending();
        for (CTask vo : cTasks) {
            //提醒分配的负责人
            msgFactory(vo.getAssignedTo(),
                    TASK_PENDING,
                    vo.getName(),
                    vo.getCreateBy(),
                    vo.getProcessingStatus(),
                    "计划任务-"+vo.getProcessingStatus(),
                    WX_TASK_DETAIL.replace("{id}",vo.getId()),
                    TASK_DETAIL
            );

        }

    }

    /**
     * 子项目--提交报价--审核提醒
     */
    private void subProjectQuoting() {
        try {
            List<CSubProject> subProjectList = cSubProjectMapper.gather(STATUS_UNDER_REVIEW);
            for (CSubProject vo : subProjectList) {
                //报价--审核中 提醒项目负责人 审核
                //通知 项目负责人
                List<SysUser> userList = getRoleUser(ROLE_PROJECT_LEADER);
                String handler = sysUserMapper.selectById(vo.getUserId()).getRealname();
                for (SysUser sysUser : userList) {
                    msgFactory(sysUser.getId(),
                            SUB_PROJECT_QUOTING,
                            vo.getSubProjectName(),
                            handler,
                            vo.getStatus(),
                            "子项目-报价-待审核",
                            WX_SUB_PROJECT_DETAIL.replace("{id}",vo.getId()),
                            SUBPROJECT_QUOTE_DETAIL.replace("{projectId}",vo.getProjectId()).replace("{subProjectId}",vo.getId())
                    );
                }



            }


        }catch (Exception e) {

        }

    }

    /**
     * 通知子项目 指派成功提醒
     */
    private void subProjectCrate() {
        try {
            List<CSubProject> subProjectList = cSubProjectMapper.gather(STATUS_QUOTING);
            for (CSubProject vo : subProjectList) {
                //报价中的 提醒相关分包商来报价
                String handler = vo.getCreateBy();
                msgFactory(vo.getUserId(),
                        SUB_PROJECT_UPLOAD,
                        vo.getSubProjectName(),
                        handler,
                        vo.getStatus(),
                        "子项目-上传报价提醒：",
                        WX_SUB_PROJECT_DETAIL.replace("{id}",vo.getId()),
                        SUBPROJECT_QUOTE_DETAIL.replace("{projectId}",vo.getProjectId()).replace("{subProjectId}",vo.getId())
                );

            }


        }catch (Exception e) {

        }

    }

    /**
     * 需求--报价审核--同意or驳回
     */
    public void additionalQuoteAudit(){
        try {
            List<CProjectQuote> quoteList = cProjectQuoteMapper.additionalByAudit();
            for (CProjectQuote vo : quoteList) {
                //提醒 提交的用户
                //查询需求
                CAdditionalRequest cAdditionalRequest = cAdditionalRequestMapper.selectById(vo.getAdditionalId());
                String handler = vo.getUpdateBy();
                msgFactory(vo.getUserId(),
                        NEED_QUOT_RESULT,
                        cAdditionalRequest.getTitle(),
                        handler,
                        vo.getStatus(),
                        "项目需求--报价审核--结果：" + vo.getStatus(),
                        null,
                        ADDITIONAL_QUOTE_DETAIL.replace("{id}",vo.getId())
                );

            }


        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 需求--提交报价--提醒
     */
    public void additionalQuoteCrate(){
        try {
            List<CProjectQuote> quoteList = cProjectQuoteMapper.additionalByGather(STATUS_UNDER_REVIEW);
            for (CProjectQuote vo : quoteList) {
                //提醒管理员审核--需求报价
                List<SysUser> userList = getRoleUser(ROLE_SUBCONTRACTORS);
                //查询需求
                CAdditionalRequest cAdditionalRequest = cAdditionalRequestMapper.selectById(vo.getAdditionalId());
                String handler = vo.getCreateBy();
                for (SysUser sysUser : userList) {
                    msgFactory(sysUser.getId(),
                            NEED_QUOT_AUDIT,
                            cAdditionalRequest.getTitle(),
                            handler,
                            vo.getStatus(),
                            "项目需求--报价-待审核",
                            null,
                            ADDITIONAL_QUOTE_DETAIL.replace("{id}",vo.getId())
                    );
                }

            }


        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 需求----报价
     */
    public void additionalQuote(){
        try {
            //收集新增的需求通知
            List<CAdditionalRequest> list =  cAdditionalRequestMapper.gather(STATUS_QUOTING);
            //通知 所有分包商
            List<SysUser> userList = getRoleUser(ROLE_SUBCONTRACTORS);
            for (CAdditionalRequest vo : list) {
                try {
                    String handler = vo.getUpdateBy();
                    for (SysUser sysUser : userList) {
                        msgFactory(sysUser.getId(),
                                NEED_QUOTING,
                                vo.getTitle(),
                                handler,
                                vo.getStatus(),
                                "项目需求--报价中",
                                WX_ADDITIONAL_REQUEST_DETAIL.replace("{id}",vo.getId()),
                                ADDITIONAL_REQUEST_DETAIL
                        );
                    }

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        } catch (Exception e) {
           // throw new RuntimeException(e);
        }
    }




    /**
     * 需求审核结果--驳回
     */
    public void additionalReject(){
        try {
            //收集成立的需求通知
            List<CAdditionalRequest> list =  cAdditionalRequestMapper.gather(STATUS_REJECT);
            //通知创建的用户
            for (CAdditionalRequest vo : list) {
                String handler = null;
                SysUser handlerUser = sysUserMapper.selectById(vo.getUserId());
                if(handlerUser != null ){
                    handler = handlerUser.getRealname();
                }
                msgFactory(vo.getUserId(),
                        NEED_REJECT,
                        vo.getTitle(),
                        handler,
                        vo.getStatus(),
                        "项目需求-驳回",
                        WX_ADDITIONAL_REQUEST_DETAIL.replace("{id}",vo.getId()),
                        ADDITIONAL_REQUEST_DETAIL
                );
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 需求审核结果--审核通过
     */
    public void additionalAudit(){
        //收集成立的需求通知
        List<CAdditionalRequest> list =  cAdditionalRequestMapper.gather(STATUS_QUOTING);
        //通知创建的用户
        for (CAdditionalRequest vo : list) {
            String handler = null;
            SysUser handlerUser = sysUserMapper.selectById(vo.getUserId());
            if(handlerUser != null ){
                handler = handlerUser.getRealname();
            }
            msgFactory(vo.getUserId(),
                    NEED_FOUND,
                    vo.getTitle(),
                    handler,
                    vo.getStatus(),
                    "项目需求-通过",
                    WX_ADDITIONAL_REQUEST_DETAIL.replace("{id}",vo.getId()),
                    ADDITIONAL_REQUEST_DETAIL
            );
        }
    }
    /**
     * 需求新增 提醒
     */
    public void additionalAdd(){
        //收集新增的需求通知
        List<CAdditionalRequest> list =  cAdditionalRequestMapper.gather(STATUS_PENDING);
        //通知 项目负责人
        List<SysUser> userList = getRoleUser(ROLE_PROJECT_LEADER);
        for (CAdditionalRequest vo : list) {
            try {
                String handler = null;
                SysUser handlerUser = sysUserMapper.selectById(vo.getUserId());
                if(handlerUser != null ){
                    handler = handlerUser.getRealname();
                }
                for (SysUser sysUser : userList) {
                    msgFactory(sysUser.getId(),
                            NEED_AUDIT,
                            vo.getTitle(),
                            handler,
                            vo.getStatus(),
                            "项目需求--待审核",
                            WX_ADDITIONAL_REQUEST_DETAIL.replace("{id}",vo.getId()),
                            ADDITIONAL_REQUEST_DETAIL
                    );
                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }


    /**
     * 根据角色 获取用户
     * @param role
     */
    private List<SysUser> getRoleUser(String role){
        List<SysUser> sysUsers = sysUserMapper.queryByOpenId(role);
        return sysUsers;
    }

    /**
     *
     * @param userId 接收者id
     * @param business  流程名称
     * @param title 标题
     * @param handler 执行人
     * @param status 业务状态
     * @param results 处理结果
     * @param url 点击跳转地址
     * @param wxUrl 微信跳转地址
     */
    private void msgFactory(String userId,
                            String business,
                            String title,
                            String handler,
                            String status,
                            String results,
                            String wxUrl,
                            String url){
        String prefix = "MSG_NOTICE:";
        String dataKey = prefix + Md5Util.md5Encode(prefix + "-" + userId + " - " + business+ " - " +title+ " - " +status+" - "+handler,"utf-8");

        if(redisUtil.hasKey(dataKey) == false){
            String openId = null;
            String email = null;
            //获取用户的openId
            CWeixin cWeixin = cWeixinMapper.findbyUserId(userId);
            if(cWeixin != null){
                openId = cWeixin.getOpenId();
            }
            //获取用户邮箱
            SysUser sysUser = sysUserMapper.selectById(userId);
            if(sysUser != null){
                email = sysUser.getEmail();
            }
            CNotice notice = CNotice.builder()
                    .userId(userId)
                    .business(business)
                    .title(title)
                    .handler(handler)
                    .status(status)
                    .results(results)
                    .url(url)
                    .wxUrl(wxUrl)
                    .wxOpenId(openId)
                    .mailNo(email)
                    .wxStatus("待发送")
                    .mailStatus("待发送")
                    .build();
            cNoticeMapper.insert(notice);
            redisUtil.set(dataKey,dataKey);//一天后过期
        }
    }

}
